/*
 * @Author: 糊涂的老知青
 * @Date: 2022-05-23
 * @Version: 1.0.0
 * @Description:
 */
package infra_domainservice

import (
	"errors"
	"lzq-admin/domain/domainservice"
	infra_model "lzq-admin/domain/model/infrastructure"
	"lzq-admin/pkg/orm"
	"lzq-admin/pkg/utility"

	"github.com/gin-gonic/gin"
)

type SystemDeptDomainService struct {
	domainservice.BaseDomainService
}

func NewDSSystemDept(c *gin.Context) *SystemDeptDomainService {
	return &SystemDeptDomainService{
		domainservice.BaseDomainService{
			GinCtx: c,
		},
	}
}

func (s *SystemDeptDomainService) Insert(inputDto infra_model.CreateSystemDeptDto) (infra_model.SystemDept, error) {
	var entity infra_model.SystemDept
	entity.SystemDeptBase = inputDto.SystemDeptBase
	entity.ID = utility.UuidCreate()
	lzqOrm := orm.NewLzqOrm(s.GinCtx)
	if p, err := lzqOrm.ISession().Insert(&entity); err != nil {
		return entity, err
	} else if p <= 0 {
		return entity, errors.New("新增部门失败")
	}
	return entity, nil
}

func (s *SystemDeptDomainService) Update(inputDto infra_model.UpdateSystemDeptDto) (infra_model.SystemDept, error) {
	var entity infra_model.SystemDept
	lzqOrm := orm.NewLzqOrm(s.GinCtx)
	if has, err := lzqOrm.QSession(true).ID(inputDto.ID).Get(&entity); err != nil {
		return entity, err
	} else if !has {
		return entity, errors.New("该部门ID不存在")
	}

	entity.SystemDeptBase = inputDto.SystemDeptBase
	if p, err := lzqOrm.USession(true).AllCols().ID(inputDto.ID).Update(&entity); err != nil {
		return entity, err
	} else if p <= 0 {
		return entity, errors.New("修改部门失败")
	}
	return entity, nil
}

func (s *SystemDeptDomainService) Delete(id string) error {
	var entity infra_model.SystemDept
	lzqOrm := orm.NewLzqOrm(s.GinCtx)
	if has, err := lzqOrm.QSession(true).ID(id).Get(&entity); err != nil {
		return err
	} else if !has {
		return errors.New("该部门ID不存在")
	}
	if p, err := lzqOrm.DSession(true).ID(id).Update(&entity); err != nil {
		return err
	} else if p <= 0 {
		return errors.New("删除部门失败")
	}
	return nil
}
